package com.whty.cms.filewps.upload.service.impl;

import com.whty.cms.filewps.common.constants.Consts;
import com.whty.cms.filewps.common.model.EsAttachment;
import com.whty.cms.filewps.common.service.CmqService;
import com.whty.cms.filewps.common.service.ICosService;
import com.whty.cms.filewps.common.service.impl.BaseAbstractServiceImpl;
import com.whty.cms.filewps.config.dto.ApplyInfo;
import com.whty.cms.filewps.config.service.IApplyInfoService;
import com.whty.cms.filewps.upload.dao.AttachFileMapper;
import com.whty.cms.filewps.upload.dao.TransformJobMapper;
import com.whty.cms.filewps.upload.dto.AttachFile;
import com.whty.cms.filewps.upload.dto.TransformJob;
import com.whty.cms.filewps.upload.service.IUploadService;
import com.whty.cms.filewps.util.*;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service(value = "uploadService")
public class UploadServiceImpl extends BaseAbstractServiceImpl<AttachFile> implements IUploadService {
	
	private static final Logger logger = LogManager.getLogger(UploadServiceImpl.class);
	
    @Autowired
    private AttachFileMapper attachFileDAO;
    
    @Autowired
    private TransformJobMapper transformJobDAO;
    
    @Autowired
    private ICosService cosService;
    
    @Autowired
    private CmqService cmqService;

    @Autowired
    private IApplyInfoService applyInfoService;

    @Override
    public AttachFile findAttchFile(Long fid) {
        return attachFileDAO.selectByPrimaryKey(fid);
    }


	public TransformJob findTransformJob(String transformId) {
		return transformJobDAO.selectByPrimaryKey(transformId);
	}


	public void insertRepeatFile(long fid, AttachFile attach) throws Exception {
		//复制附件表信息并插入数据库
		String sFid = String.valueOf(fid);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		JSONObject fileInfo = EsUtil.searchDoc(sFid);
		
		String fileExt = "";
		if (attach.getFileName().contains(".")) {
			fileExt = attach.getFileName().substring(attach.getFileName().lastIndexOf(".") + 1, attach.getFileName().length());
		}
		attach.setFileExt(fileExt);		
		attach.setFileLength(fileInfo.optLong("fileLength"));
		attach.setFileSize(fileInfo.optString("fileSize"));
		attach.setPostedTime(new Date());
		attach.setStatus(fileInfo.optString("status"));
		attach.setFilePath(fileInfo.optString("filePath"));
		attach.setTransformId(fileInfo.optString("transformId"));
		attach.setThumbnailId(fileInfo.optString("thumbnailId"));
		attach.setYunType(fileInfo.optString("yunType"));
		attach.setUploadId(fileInfo.optString("uploadId"));
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
		JSONObject tableAtt = JSONObject.fromObject(attach,jsonConfig);
		tableAtt.put(Consts.TABLE_TYPE, Consts.TABLE_ATTACHMENT);
		try {
			cmqService.sendMsg(MemcacheUtil.getDatabaseObj(Consts.CMQ_ATTACHMENT_QUEUE), tableAtt.toString());
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		
		//复制es信息并插入到es
		
		fileInfo.put("fid", attach.getFid());
		fileInfo.put("fileName", attach.getFileName());
		fileInfo.put("userId", attach.getUserId());
		fileInfo.put("postedTime", sdf.format(attach.getPostedTime()));
		fileInfo.put("applyType", attach.getApplyType());
		fileInfo.put("sourceType", attach.getSourceType());
		fileInfo.put("platformCode", attach.getPlatformCode());
		EsUtil.addOrUpdateDoc(String.valueOf(attach.getFid()),fileInfo.toString());
		
	}

	
	public AttachFile finishUploadFile(AttachFile attach) throws Exception {
		if(attach.getFid()==null){
			attach.setFid(SnowFlakeUtil.getNextId());
		}
		attach.setStatus("1");  //正常状态
		attach.setYunType("1");  //1表示腾讯云，后期会扩展
		attach.setPostedTime(new Date());
		String fileName = attach.getFileName();
		String fileExt = "";
		if (fileName.contains(".")) {
			fileExt = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		}
		attach.setFileExt(fileExt);
		
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
		EsAttachment es = new EsAttachment(attach);
		JSONObject esObj = JSONObject.fromObject(es,jsonConfig);
		EsUtil.addOrUpdateDoc(String.valueOf(attach.getFid()), esObj.toString());
		logger.info("插入ES完成，相关文件信息为============="+JSONObject.fromObject(attach).toString());
		cosService.handVTS(attach);
//		Thread.sleep(1000);
		return attach;
	}


	public boolean saveTransformInfo(JSONObject data) throws Exception {
		boolean flag = false;
		JSONObject es = cosService.getTransformInfoNew(data);
		if(null != es) {
			String transformId = es.optString("transformId");
			//此处不修改转码任务的数据库，因为可能出现转码完成以后数据还没有插入，通过转码id查询数据可能为null导致报错
			/*TransformJob job = transformJobDAO.selectByPrimaryKey(transformId);
			job.setTransformStatus("1");  //转码完成
			job.setTransFileLength(es.optLong("transFileLength"));
			job.setPreviewUrl(es.optString("previewUrl"));
			job.setDuration(es.optInt("duration"));
			job.setThumnailUrl(es.optString("thumnailUrl"));*/
			
			TransformJob job = new TransformJob();
			job.setTransformId(transformId);
			job.setTransformStatus("1");  //转码完成
			job.setTransFileLength(es.optLong("transFileLength"));
			job.setPreviewUrl(es.optString("previewUrl"));
			job.setDuration(es.optInt("duration"));
			job.setThumnailUrl(es.optString("thumbnailUrl"));
			logger.info("回调后调用cmq更新转码表："+JSONObject.fromObject(job).toString());
			try {
				cmqService.sendMsg(MemcacheUtil.getDatabaseObj(Consts.CMQ_ATTACHMENT_RET_QUEUE), JSONObject.fromObject(job).toString());
				flag = true;
			} catch (Exception e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			}
		}
		return flag;
	}


	public AttachFile SimpleUploadFile(AttachFile attach, InputStream in) throws Exception {
		try {
			CosUtil.sampleUpload(attach,in);
			finishUploadFile(attach);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return attach;
	}

	@Override
	public void fixBucketNameISNull(String fid) {
		JSONObject data = EsUtil.searchDoc(fid);
		String bucketName = data.getString("bucketName");
		String fileExtType = data.getString("fileExtType");
		if(StringUtils.isBlank(bucketName)) {
			bucketName = MemcacheUtil.getDatabaseObj(data.getString("applyType")+"-"+Consts.SOURCE_BUCKET);
			data.put("bucketName",bucketName);
		}
		String downloadUrl;
		String filePath = data.getString("filePath");
		String applyType = data.getString("applyType");
		if("0".equals(MemcacheUtil.getDatabaseObj(bucketName))) {
			downloadUrl = CosUtil.getAuthDownloadUrlForPrivate(filePath,applyType);
		}else {
			downloadUrl = CosUtil.getAuthDownloadUrl(filePath,applyType);
		}
		data.put("downloadUrl", downloadUrl);
		EsUtil.addOrUpdateDoc(fid, data.toString());
		if(fileExtType.equals("video") &&  StringUtils.isBlank(data.getString("transformStutas"))) {
			ApplyInfo applyInfo = applyInfoService.findOneById(data.getString("applyType"));
			if(applyInfo != null && StringUtils.isBlank(applyInfo.getTransformFlag())) {
				//触发转码
				try {
					cosService.transformForFid(data);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}

	@Override
	public boolean saveTransformInfoForV5(String fid, cn.hutool.json.JSONObject data) throws Exception {
		boolean flag = false;
		//更新es中的数据
		JSONObject es = cosService.getTransformInfoForV5(fid,data);
		if(null != es && es.getString("transformStutas").equals("1")) {
			String transformId = es.optString("transformId");
			TransformJob job = new TransformJob();
			job.setTransformId(transformId);
			job.setTransformStatus("1");  //转码完成
			job.setTransFileLength(es.optLong("transFileLength"));
			job.setPreviewUrl(es.optString("previewUrl"));
			job.setDuration(es.optInt("duration"));
			job.setThumnailUrl(es.optString("thumbnailUrl"));
			logger.info("回调后调用cmq更新转码表："+JSONObject.fromObject(job).toString());
			try {
				cmqService.sendMsg(MemcacheUtil.getDatabaseObj(Consts.CMQ_ATTACHMENT_RET_QUEUE), JSONObject.fromObject(job).toString());
				flag = true;
			} catch (Exception e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			}
		}
		return flag;
	}

}
